var groupArray = require('group-array');

var arr = [
  {tag: 'one', content: 'A'},
  {tag: 'one', content: 'A'},
  {tag: 'two', content: 'C'},
  {tag: 'two', content: 'D'},
  {tag: 'three', content: 'E'},
  {tag: 'three', content: 'E'},
  {tag: undefined, name: '刘阿勇', age: 22},
  {tag: null, name: '张三', age: 22},
];

// group by the `tag` property
	var ret = groupArray(arr, 'tag');
	console.log(Object.keys(ret))
	console.log(ret)
	console.log('-----------------------\n')


	/*
	// group by the `tag` property
	var ret = groupArray(arr, 'tag', 'content', 'tag');
	console.log(Object.keys(ret))
	console.log(JSON.stringify(ret, null, 2))
	console.log('-----------------------\n')
	*/

	var ret1 = groupBy(arr, 'tag');
	console.log(ret1)
	console.log('-----------------------\n')
	console.log(groupBy(ret1, 'tag'))
	
	var property = 'content'
	for(var i in ret1) {
		ret1[i] =  groupBy(ret1[i], property)
	}
	console.log(JSON.stringify(ret1, null, 2))
	



function test1 () {
	// group by the `tag` property
	var ret = groupArray(arr, 'tag');
	console.log(Object.keys(ret))
	console.log(ret)
	console.log('-----------------------\n')
	var ret = arrayGroup(arr, 'tag');
	console.log(Object.keys(ret))
	console.log(ret)

}

function arrayGroup(arr, property) {
	return arrayGroupV1.apply(null, arguments)
}

/**
 * 给数组按照某个属性进行分组
 * @param  {[type]} arr      [description]
 * @param  {[type]} property [description]
 * @return {[type]}          [description]
 */
function arrayGroupV1(arr, property) {
	return arr.reduce((obj, ele) => {
		var key = ele[property]
		if(key == null){
			return obj 
		}

		if(obj[key]) {
			obj[key].push(ele)
		}else {
			obj[key] = [ele]
		}
		return obj
	}, {})
}


/**
 * 将数组按照某一个元素进行分组
 * 
 * @param  {[type]} arr  [description]
 * @param  {[type]} prop [description]
 * @return {[type]}      [description]
 */
function groupBy(arr, prop){
	var obj = {}
	var one, propVal ;
	for (var i = 0; i < arr.length; i++) {
		one = arr[i]
		propVal = one[prop]

		if(propVal == null) {
			continue
		}

		if(!obj[propVal]) {
			obj[propVal] = []
		}
		obj[propVal].push(one)

	}
	return obj
}

function arrayGroupV1(arr, props) {
	return arr.reduce((obj, ele) => {
		var key = ele[props]
		if(key == null){
			return obj 
		}

		if(obj[key]) {
			obj[key].push(ele)
		}else {
			obj[key] = [ele]
		}
		return obj
	}, {})
}

